package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
	"backend-api/pkg/utils"
)

// User 前台用户模型
type User struct {
	ID        uint      `json:"id" gorm:"primaryKey;autoIncrement"`
	UUID      string    `json:"uuid" gorm:"type:varchar(36);uniqueIndex;not null"`
	Username  string    `json:"username" gorm:"type:varchar(50);uniqueIndex;not null"`
	Email     string    `json:"email" gorm:"type:varchar(100);uniqueIndex;not null"`
	Password  string    `json:"-" gorm:"type:varchar(255);not null"`
	Nickname  string    `json:"nickname" gorm:"type:varchar(50)"`
	Avatar    string    `json:"avatar" gorm:"type:varchar(255)"`
	Phone     string    `json:"phone" gorm:"type:varchar(20);index"`
	Gender    int       `json:"gender" gorm:"type:tinyint;default:0;comment:'0:未知,1:男,2:女'"`
	Birthday  *time.Time `json:"birthday" gorm:"type:date"`
	Status    int       `json:"status" gorm:"type:tinyint;default:1;comment:'0:禁用,1:正常'"`
	LastLogin *time.Time `json:"last_login" gorm:"type:datetime"`
	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

// BeforeCreate GORM钩子：创建前生成UUID
func (u *User) BeforeCreate(tx *gorm.DB) error {
	if u.UUID == "" {
		u.UUID = uuid.New().String()
	}
	return nil
}

// TableName 指定表名
func (User) TableName() string {
	return "users"
}

// UserResponse 用户响应结构（不包含敏感信息）
type UserResponse struct {
	ID        uint                `json:"id"`
	UUID      string              `json:"uuid"`
	Username  string              `json:"username"`
	Email     string              `json:"email"`
	Nickname  string              `json:"nickname"`
	Avatar    string              `json:"avatar"`
	Phone     string              `json:"phone"`
	Gender    int                 `json:"gender"`
	Birthday  utils.CustomTimePtr `json:"birthday"`
	Status    int                 `json:"status"`
	LastLogin utils.CustomTimePtr `json:"last_login"`
	CreatedAt utils.CustomTime    `json:"created_at"`
	UpdatedAt utils.CustomTime    `json:"updated_at"`
}

// ToResponse 转换为响应结构
func (u *User) ToResponse() *UserResponse {
	return &UserResponse{
		ID:        u.ID,
		UUID:      u.UUID,
		Username:  u.Username,
		Email:     u.Email,
		Nickname:  u.Nickname,
		Avatar:    u.Avatar,
		Phone:     u.Phone,
		Gender:    u.Gender,
		Birthday:  utils.NewCustomTimePtr(u.Birthday),
		Status:    u.Status,
		LastLogin: utils.NewCustomTimePtr(u.LastLogin),
		CreatedAt: utils.NewCustomTime(u.CreatedAt),
		UpdatedAt: utils.NewCustomTime(u.UpdatedAt),
	}
}